package com.qdlc.p2p.biz.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.qd.p2p.sina.pay.enums.AccountType;
import com.qd.p2p.sina.pay.enums.IdentityType;
import com.qd.p2p.sina.pay.enums.PayType;
import com.qd.p2p.sina.pay.param.CreateHostingCollectTradeParam;
import com.qd.p2p.sina.pay.param.CreateSingleHostingPayTradeParam;
import com.qd.p2p.sina.pay.param.DepositExtendParam;
import com.qd.p2p.sina.pay.response.CreateHostingCollectTradeResponse;
import com.qd.p2p.sina.pay.response.CreateSingleHostingPayTradeResponse;
import com.qd.p2p.sina.service.SinaPayService;
import com.qdlc.p2p.biz.service.AccountService;
import com.qdlc.p2p.biz.service.BaseGiveAwardService;
import com.qdlc.p2p.biz.service.MovieConfigService;
import com.qdlc.p2p.biz.util.NotifyRequestUrl;
import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.constant.SinaConstant;
import com.qdlc.p2p.common.constant.Summary;
import com.qdlc.p2p.common.constant.TradeCode;
import com.qdlc.p2p.common.enums.EnumActicityPlanNid;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.OrderNoUtil;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dao.MovieConfigDao;
import com.qdlc.p2p.dal.dao.TppDao;
import com.qdlc.p2p.dal.dao.TppTradeLogDao;
import com.qdlc.p2p.dal.dao.UserDao;
import com.qdlc.p2p.dal.dto.*;
import com.qdlc.p2p.dal.model.BaseGiveAwardModel;
import com.qdlc.p2p.dal.model.MovieConfigModel;
import com.qdlc.p2p.dal.model.TppModel;
import com.qdlc.p2p.dal.model.TppTradeLogModel;
import com.qdlc.p2p.dal.util.SystemConfigs;

@Service("movieConfigService")
public class MovieConfigServiceImpl implements MovieConfigService {
	
	@Resource
	private MovieConfigDao movieConfigDao;

	@Resource
	private UserDao userDao;

	@Resource
	private SinaPayService sinaPayService;

	@Resource
	private TppTradeLogDao tppTradeLogDao;

	@Resource
	private TppDao tppDao;

	@Resource
	@Qualifier("giveUserMovieTicketService")
	private BaseGiveAwardService giveUserMovieTicketService;

	@Resource
	private AccountService accountService;

	@Override
	public List<MovieConfig> findAll() {
		return movieConfigDao.findAll();
	}

	@Override
	public PageDataList<MovieConfigModel> list(MovieConfigModel model) {
		PageDataList<MovieConfig> plist =  movieConfigDao.list(model);
		PageDataList<MovieConfigModel> pageDataList = new PageDataList<MovieConfigModel>();
		List<MovieConfigModel> list = new ArrayList<MovieConfigModel>();
		pageDataList.setPage(plist.getPage());
		if (plist.getList().size() > 0) {
			for (int i = 0; i < plist.getList().size(); i++) {
				MovieConfig c = plist.getList().get(i);
				MovieConfigModel cm = MovieConfigModel.instance(c);
				list.add(cm);
			}
		}
		pageDataList.setList(list);
		
		return pageDataList;
	}

	@Override
	public MovieConfig find(long id) {
		return movieConfigDao.find(id);
	}

	@Override
	public void add(MovieConfig MovieConfig) {
		movieConfigDao.save(MovieConfig);
	}

	@Override
	public void update(MovieConfig MovieConfig) {
		movieConfigDao.update(MovieConfig);
	}
	
	@Override
	public void addColTraMovTic(long userId, double money, long id,int moviePages) {
		
		User user = userDao.find(userId);
		// 订单号
		String orderNo = OrderNoUtil.getInstance().getSerialNumber();
		if(money > 0){ 
			String tppUserCustId = user.getTppUserCustId();
			HashMap<String, Object> data = new HashMap<String, Object>();
			data.put("id", id);
			data.put("moviePages", moviePages);
			data.put("money", money);
			String memo = JSON.toJSONString(data);
			TppTradeLog tppTradeLog = new TppTradeLog(tppUserCustId, SystemConfigHelper.getValue(SystemConfigHelper.Nid.SELL_MOVIE_CUST_ID), SinaConstant.IDENTITY_TYPE_UID, money, 0, orderNo,
					SinaConstant.TRADE_STATUS_WAIT_PAY, SinaConstant.TRADE_CODE_1001, SinaConstant.BUY_MOVIE_TICKETS,
					id,0,"",memo);

	        tppTradeLog.setAddTime(DateUtil.getNow());
	        tppTradeLogDao.save(tppTradeLog);
	        String serviceType = tppTradeLog.getServiceType();
	        Tpp tpp = new Tpp(TppTradeLogModel.getTppServiceType(serviceType), serviceType, user, null, tppTradeLog.getMoney(), null, tppTradeLog.getOrderNo(), tppTradeLog.getBorrowId() + "");
	        if (tppTradeLog.getIdentityType() == SinaConstant.IDENTITY_TYPE_EMAIL) {
	            tpp.setTppUserCustId(tppTradeLog.getTppUserCustId());
	        }
	        TppModel tppModel = TppModel.instance(tpp);
	        tppModel.setOut_trade_code(tppTradeLog.getTradeType());
	        String summary = Summary.getSummaryNameByType(serviceType);
	        tppModel.setSummary(summary);
	        tppModel.setCan_repay_on_failed(SinaConstant.SINA_YES);
	        tppModel.setIdentityType(tppTradeLog.getIdentityType());
	    
			// 代收请求开始
			CreateHostingCollectTradeParam param = new CreateHostingCollectTradeParam();
	        param.setOutTradeNo(orderNo)
	                .setOutTradeCode(TradeCode.C1001)
	                .setPayerId(tppUserCustId)
	                .setPayerIdentityType(IdentityType.UID)
	                .setAmount(money)
	                .setPayerIp(Global.getIP())
	                .setSummary(summary)
	                .setCanRepayOnFailed(SinaConstant.SINA_YES)
	                .setNotifyUrl(NotifyRequestUrl.COLLECT_TRADE_MOV_TIC_NOTIFY_URL);
	        DepositExtendParam extend = new DepositExtendParam();
	        extend.setPayType(PayType.balance);
	        if (AccountType.BASIC.equals(SystemConfigHelper.getValue(SystemConfigHelper.Nid.ACCOUNT_TYPE))) {
	        	extend.setAccountType(AccountType.BASIC);
	        } else {
	        	extend.setAccountType(AccountType.SAVING_POT);
	        }
	        param.setPayParam(extend);
	        CreateHostingCollectTradeResponse collTrade = null;
	        try {
	        	collTrade = sinaPayService.createHostingCollectTrade(param);
	            tppModel.setStatus(TppModel.STATUS_SUCEESS);
	            tppModel.setRespDesc("代收处理成功");
	        } catch (Exception e) {
	            tppModel.setStatus(TppModel.STATUS_FAIL);
	            tppModel.setRespDesc(e.getMessage());
	            e.printStackTrace();
	        } finally {
	            if (!SinaConstant.TRADE_SERVICE_AUTO_TENDER.equals(serviceType) &&
	                    !SinaConstant.TRADE_SERVICE_TENDER.equals(serviceType)) {
	                tppDao.save(tppModel.prototype());
	            }
	        }
			
			if (collTrade != null && !(SinaConstant.TRADE_STATUS_FAILED.equals(collTrade.getTradeStatus()))) {
				//更新电影票已售数量
				movieConfigDao.updateByMoviePages(moviePages,id);
				// 先扣除购买金额
				Global.setTransfer("web_url", SystemConfigHelper.getValue(SystemConfigHelper.Nid.WEB_URL));
				accountService.deductUseMoneyAndTotal(userId, SystemConfigs.ADMIN_ID, money);
				/*// 获取电影票
				try {
					int validDay = 60;// 电影票有效期限（天）
					double count = moviePages;
					//BaseGiveAwardModel baseGiveAwardModel = new BaseGiveAwardModel(user, count, EnumActicityPlanNid.BUY_MOVIE_TICKET.getValue(), validDay, "购买电影票");
					//giveUserMovieTicketService.giveSingleUserAward(baseGiveAwardModel);
				} catch (Exception e) {
					e.printStackTrace();
				}*/
			}
		 }
	}
	
    @Override
    public CreateSingleHostingPayTradeResponse movTicpayTrade(TppTradeLog tppTradeLog) {
        if (SinaConstant.BUY_MOVIE_TICKETS.equals(tppTradeLog.getServiceType())) {
            return doMovTicpayTrade(tppTradeLog);
        } else {
            return null;
        }
    }
    
    /**
     * 购买电影票 代付方法
     *
     * @param tppTradeLog
     * @param
     * @return
     */
    private CreateSingleHostingPayTradeResponse doMovTicpayTrade(TppTradeLog tppTradeLog) {

        String serviceType = tppTradeLog.getServiceType();
        double amount = tppTradeLog.getMoney();
        String toTppUserCustId = tppTradeLog.getToTppUserCustId();
        String tppUserCustId = tppTradeLog.getTppUserCustId();
        User user = userDao.findByTppCustId(tppUserCustId);
        User toUser = userDao.findByTppCustId(toTppUserCustId);
		Tpp tpp = new Tpp(SinaConstant.SELL_MOVIE_TICKETS, SinaConstant.SELL_MOVIE_TICKETS, user, toUser, amount, null);
        TppModel tppModel = TppModel.instance(tpp);
        String tradeCode = SinaConstant.TRADE_CODE_2001;
        tppModel.setOut_trade_code(tradeCode);
        tppModel.setSummary(Summary.getSummaryNameByType(serviceType));
        CreateSingleHostingPayTradeResponse payTrade = null;
        String outOrderNo = tppModel.getOrderId();
        try {
            String payeeIdentityId = toTppUserCustId;
            AccountType accountType = AccountType.SAVING_POT;
            TradeCode outTradeCode = TradeCode.C2001;
            String summary = TppModel.SELL_MOVIE_TICKETS_STR;
            String goodsId = tppModel.getTppBorrowId();
            List<TppSinaSplit> sl = tppModel.getSplit_list();
            String splitList = TppSinaSplit.getSplitList(sl,SystemConfigHelper.getValue(SystemConfigHelper.Nid.MEMBER_EMAIL));
            String notifyUrl = NotifyRequestUrl.PAY_TRADE_MOV_TIC_NOTIFY_URL;
            CreateSingleHostingPayTradeParam param = new CreateSingleHostingPayTradeParam();
            param.setOutTradeNo(outOrderNo)
                    .setPayeeIdentityId(payeeIdentityId)
                    .setPayeeIdentityType(IdentityType.UID)
                    .setOutTradeCode(outTradeCode)
                    .setGoodsId(goodsId)
                    .setAmount(amount)
                    .setSummary(summary)
                    .setSplitList(splitList)
                    .setAccountType(accountType)
                    .setNotifyUrl(notifyUrl);
            payTrade = sinaPayService.createSingleHostingPayTrade(param);
            
            if(payTrade == null)
            {
                tpp.setStatus(TppModel.STATUS_FAIL);
                tpp.setRespDesc("代付处理失败");
            } else {
                tpp.setStatus(TppModel.STATUS_SUCEESS);
                tpp.setRespDesc("代付处理成功");
            }
        } catch (Exception e) {
            tpp.setStatus(TppModel.STATUS_FAIL);
            tpp.setRespDesc("代付处理失败");
            e.printStackTrace();
        } finally {
        	// 调度任务
        	tppModel.setStatus(tpp.getStatus());
			tppModel.setRespDesc(tpp.getRespDesc());
			tppModel.setTppBorrowId(tppTradeLog.getBorrowId()+"");
			tppModel.setAssociateOrderId(tppTradeLog.getOrderNo());
            tppDao.save(tppModel.prototype());
        }

        // 生成代收购买电影票的TppTradeLog
        TppTradeLog newTppTradeLog = new TppTradeLog();
        newTppTradeLog.setTppUserCustId(tppUserCustId);
        newTppTradeLog.setToTppUserCustId(toTppUserCustId);
        newTppTradeLog.setIdentityType(SinaConstant.IDENTITY_TYPE_UID);
        newTppTradeLog.setMoney(amount);
        newTppTradeLog.setOrderNo(outOrderNo);
        newTppTradeLog.setTradeStatus(SinaConstant.TRADE_STATUS_PAY_FINISHED);
        newTppTradeLog.setTradeType(tradeCode);
        newTppTradeLog.setServiceType(SinaConstant.SELL_MOVIE_TICKETS);
        newTppTradeLog.setBorrowId(tppTradeLog.getBorrowId());
        newTppTradeLog.setBorrowRepaymentId(0);
        newTppTradeLog.setSplitList(null);
        newTppTradeLog.setMemo(tppTradeLog.getMemo());
        newTppTradeLog.setTradeTime(DateUtil.getNow());
        newTppTradeLog.setAddTime(DateUtil.getNow());
        tppTradeLogDao.save(newTppTradeLog);
        return payTrade;
    }
}
